import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { NzModalRef, NzMessageService, NzNotificationService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFUISchema } from '@delon/form';
import { Observable, of, zip } from 'rxjs';
import { catchError } from 'rxjs/operators';

/**
 * 数据源添加/修改
 */
@Component({
  selector: 'app-prodyear-edit',
  templateUrl: './product-year-edit.component.html',
})
export class ProductYearEditComponent implements OnInit {
  brands = [];
  brandTypes = [];
  years = [];

  @Input()
  record: any = {};
  i: any;
  schema: SFSchema = {
    properties: {},
  };
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 100,
      grid: { span: 12 },
    },
  };

  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    private notice: NzNotificationService,
  ) {}

  ngOnInit(): void {
    for (let i = new Date().getFullYear() + 1; i >= 2012; i--) {
      this.years.push(i + '');
    }
    const api = [this.http.get(`/cf/prod/sys-prod/brands`)];
    zip(...api)
      .pipe(
        catchError(([brands]) => {
          return [brands];
        }),
      )
      .subscribe(([brands]) => {
        this.brands = brands.data;
        this.buildSf();
        if (this.record.id) {
          this.http.get(`/cf/prod/sys-prod/prodyear/${this.record.id}`).subscribe(res => {
            this.i = res.data;
            this.i.stime = this.i.startTime.split(' ')[0];
            this.i.etime = this.i.endTime.split(' ')[0];
          });
        }
      });
  }

  buildSf() {
    this.schema = {
      properties: {
        year: {
          type: 'string',
          title: '年份',
          enum: this.years,
        },
        brand: { type: 'string', title: '品牌', enum: this.brands },
        stime: { type: 'string', title: '开始日期', format: 'date' },
        etime: { type: 'string', title: '结束日期', format: 'date' },
      },
      required: ['year', 'brand', 'stime', 'etime'],
    };
  }

  save(value: any) {
    const req: Observable<string> = this.record.id
      ? this.http.put('/cf/prod/sys-prod/prodyear', value)
      : this.http.post(`/cf/prod/sys-prod/prodyear`, value);

    req.pipe(catchError(err => of(err))).subscribe(res => {
      if (res.status === 200) {
        this.notice.success('成功', '保存成功');
        this.modal.close(true);
      }
    });
  }

  close() {
    this.modal.destroy();
  }
}
